package io.object_stream;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ObjectStreamDemo {
    private static final String TMP_FILE = "box.tmp";


    public static void main(String[] args) {
        testWrite();
        testRead();
    }
    private static void testRead(){
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(TMP_FILE));
            System.out.println(ois.readBoolean());
            System.out.println(ois.readByte());
            System.out.println(ois.readChar());
            System.out.println(ois.readInt());
            System.out.println(ois.readFloat());
            System.out.println(ois.readObject());
            HashMap map = (HashMap) ois.readObject();
            Iterator iter = map.entrySet().iterator();

            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry)iter.next();
                System.out.printf("%-6s -- %s\n" , entry.getKey(), entry.getValue());
            }

        } catch (Exception e) {

        }
    }

    private static void testWrite(){
        try {

            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(TMP_FILE)
            );
            oos.writeBoolean(true);
            oos.writeByte((byte)65);
            oos.writeChar('a');
            oos.writeInt(20131015);
            oos.writeFloat(3.14F);

            HashMap map = new HashMap();
            map.put("one", "red");
            map.put("two", "green");
            map.put("three", "blue");
            oos.writeObject(map);
            Box box = new Box("desk", 80, 48);
            oos.writeObject(box);
            oos.close();
        } catch (Exception e) {

        }
    }




}
class Box implements Serializable{
    private int width;
    private int height;
    private String name;

    public Box(String name, int width, int height) {
        this.name = name;
        this.width = width;
        this.height = height;
    }

    @Override
    public String toString() {
        return "["+name+": ("+width+", "+height+") ]";
    }
}